#include "xyaccount.h"

#include <QVariantMap>

XyAccount::XyAccount(QObject *parent) : QObject(parent)
{

}

void XyAccount::callState(XyCall *pcall, QVariantMap xyParam)
{
    XyCall* xySip = nullptr;
    if(xyParam.isEmpty() || !pcall)
    {
        return;
    }
    pjsip_inv_state xyState = (pjsip_inv_state)xyParam.value("sipSate").toInt();
    if(PJSIP_INV_STATE_DISCONNECTED == xyState)
    {
        std::lock_guard<std::mutex> xyLock(m_mutex);
        std::list<XyCall*>::iterator it;
        for(it = m_lstCall.begin(); it != m_lstCall.end(); ++it)
        {
            if(*it == pcall)
            {
                xySip = *it;
                m_lstCall.remove(*it);
                break;
            }
        }
    }
    if(xySip)
    {
        delete xySip;
    }
}

void XyAccount::answer(XyCall *pCall)
{
    if(pCall)
    {
        pj::CallOpParam xyOp;
        xyOp.statusCode = PJSIP_SC_OK;
        pCall->answer(xyOp);
    }
}

void XyAccount::holdon(const QVariantMap &xyParam)
{

}


void XyAccount::onIncomingCall(pj::OnIncomingCallParam &prm)
{
    XyCall* psip = nullptr;
    {
        std::lock_guard<std::mutex> xyLock(m_mutex);
        if(m_lstCall.empty())
        {
           psip = new XyCall(*this, nullptr, prm.callId);
           m_lstCall.push_back(psip);
        }

    }
    if(psip)
    {
        pj::CallOpParam xyOp;
        xyOp.statusCode = PJSIP_SC_PROGRESS;
        psip->answer(xyOp);
    }
    else
    {
        pj::Account::onIncomingCall(prm);
    }
}

void XyAccount::onRegState(pj::OnRegStateParam &prm)
{
    pj::Account::onRegState(prm);
    QVariantMap xyParam;
    xyParam.insert("sipCode", QString::number(prm.code));
    xyParam.insert("sipReason", QString(prm.reason.c_str()));
    xyParam.insert("sipState",QString(prm.status));
}


void XyAccount::onRegStarted(pj::OnRegStartedParam &prm)
{
    pj::Account::onRegStarted(prm);
}

void XyAccount::onIncomingSubscribe(pj::OnIncomingSubscribeParam &prm)
{
     pj::Account::onIncomingSubscribe(prm);
}

void XyAccount::onInstantMessage(pj::OnInstantMessageParam &prm)
{
     pj::Account::onInstantMessage(prm);
}

void XyAccount::onInstantMessageStatus(pj::OnInstantMessageStatusParam &prm)
{
     pj::Account::onInstantMessageStatus(prm);
}

void XyAccount::onTypingIndication(pj::OnTypingIndicationParam &prm)
{
     pj::Account::onTypingIndication(prm);
}

void XyAccount::onMwiInfo(pj::OnMwiInfoParam &prm)
{
     pj::Account::onMwiInfo(prm);
}
